<template>
  <div class="waitersBox">
    <div class="waitersHeader">
      <div class="waitersHeader-body">
        <el-form ref="listQuery" :inline="true" :model="listQuery">
          <el-form-item label="管理单位">
            <el-select v-model="listQuery.management" placeholder="区域" clearable>
              <el-option v-for="item in managementOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所在区域">
            <el-select v-model="listQuery.region" placeholder="设备编号" clearable>
              <el-option v-for="item in regionOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所在站点">
            <el-select v-model="listQuery.site" placeholder="管理人员" clearable>
              <el-option v-for="item in siteOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="所在管线">
            <el-select v-model="listQuery.pipeline" placeholder="区域" clearable>
              <el-option v-for="item in pipelineOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <!--          <el-form-item label="所属省份">
            <el-select v-model="listQuery.province" placeholder="省份" clearable>
              <el-option v-for="item in provinceOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>-->
        </el-form>
        <el-form ref="listQuery" :inline="true" :model="listQuery">
          <el-form-item label="排列顺序">
            <el-select v-model="listQuery.sort" @change="handleFilter">
              <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户姓名">
            <el-input v-model="listQuery.username" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">
              查询
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-edit" @click="handleCreate">
              添加
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button v-waves :loading="downloadLoading" type="primary" icon="el-icon-download" @click="handleDownload">
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </div>

    </div>
    <div class="administrationBody">
      <div class="administrationBodyTable">
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @sort-change="sortChange"
        >
          <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
            <template slot-scope="{row}">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户名" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.username }}</span>
            </template>
          </el-table-column>
          <el-table-column label="权限" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.limits }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="管理单位" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.management }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.phone }}</span>
            </template>
          </el-table-column>
          <el-table-column label="Email" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.email }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属区域" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.region }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属管线" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.pipeline }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属站点" min-width="50px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.site }}</span>
            </template>
          </el-table-column>
          <el-table-column label="注册时间" min-width="80px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.time | parseTime('{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="80px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设置" align="center" min-width="100" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleUpdate(row)">
                编辑
              </el-button>
              <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.amount" @pagination="getList" />
    </div>
    <div class="administrationFooter">
      <div>
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:70px;">

            <el-form-item label="用户名" prop="username">
              <el-input v-model="temp.username" />
            </el-form-item>
            <el-form-item label="权限" prop="limits">
              <el-select v-model="temp.limits" placeholder="权限" style="width:280px" @change="handleFilter">
                <el-option v-for="item in limitsOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>

            <el-form-item label="姓名" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
            <el-form-item label="管理单位" prop="management">
              <el-select v-model="temp.management" placeholder="管理单位" style="width:280px" @change="handleFilter">
                <el-option v-for="item in managementOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="temp.phone" />
            </el-form-item>

            <el-form-item label="Email" prop="email">
              <el-input v-model="temp.email" />
            </el-form-item>
            <el-form-item label="所属区域" prop="region">
              <el-select v-model="temp.region" placeholder="所属区域" style="width:280px" @change="handleFilter">
                <el-option v-for="item in regionOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属管线" prop="pipeline">
              <el-select v-model="temp.pipeline" placeholder="所属管线" style="width:280px" @change="handleFilter">
                <el-option v-for="item in pipelineOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>
            <el-form-item label="所属站点" prop="site">
              <el-select v-model="temp.site" placeholder="所属站点" style="width:280px" @change="handleFilter">
                <el-option v-for="item in siteOptions" :key="item.key" :label="item.label" :value="item.key" />
              </el-select>
            </el-form-item>

            <el-form-item label="注册时间" prop="time">
              <el-date-picker v-model="temp.time" type="datetime" style="width:280px" placeholder="请选择一个时间" :picker-options="pickerOptions0" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" style="width:400px" type="textarea" placeholder="请输入" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">
              关闭
            </el-button>
            <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
              提交
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchList, createWaiters, updateWaiters, deleteWaiters, fetchOptions } from '@/api/waiters'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { validEmail } from '@/utils/validate'
export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },

  data() {
    const validatePhone = (rule, value, callback) => {
      if (value.length !== 11) {
        callback(new Error('请输入正确的手机号!'))
      } else {
        callback()
      }
    }

    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的Email'))
      } else {
        callback()
      }
    }

    return {
      // 时间范围限制
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        amount: 10,
        username: '',
        sort: '+id',
        phone: '',
        region: '',
        site: '',
        pipeline: '',
        management: ''
      },
      importanceOptions: [1, 2, 3],
      // calendarTypeOptions,
      sortOptions: [{ label: 'ID 升序', key: '+id' }, { label: 'ID 降序', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: '',
        username: '',
        limits: '',
        name: '',
        management: '',
        phone: '',
        email: '',
        pipeline: '',
        site: '',
        time: new Date(),
        remark: '',
        region: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        time: [{ type: 'date', required: true, message: '请选择时间', trigger: 'change' }],
        username: [{ required: true, message: '用户名错误', trigger: 'blur' }],
        limits: [{ required: true, message: '请选择权限', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        management: [{ required: true, message: '请输入单位', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入正确的手机号', trigger: 'blur', validator: validatePhone }],
        pipeline: [{ required: true, message: '请输入管线', trigger: 'blur' }],
        site: [{ required: true, message: '请输入站点', trigger: 'blur' }],
        email: [{ required: true, message: '请输入正确的Email', trigger: 'blur', validator: validateEmail }],
        region: [{ required: true, message: '请选择区域', trigger: 'blur' }]
      },
      downloadLoading: false,
      regionOptions: '',
      siteOptions: '',
      pipelineOptions: '',
      managementOptions: '',
      limitsOptions: ''
    }
  },
  created() {

  },
  mounted() {
    this.getList()
    this.getAllOptions()
  },
  methods: {

    getList() {
      this.listLoading = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },

    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },

    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    resetTemp() {
      this.temp = {
        id: '',
        username: '',
        limits: '',
        name: '',
        management: '',
        phone: '',
        pipeline: '',
        site: '',
        email: '',
        time: new Date(),
        remark: '',
        region: ''
      }
    },

    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createWaiters(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.time = new Date(this.temp.time)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      this.getList()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.time = +new Date(tempData.time) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateWaiters(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改完成',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleDelete(row, index) {
      this.getList()
      const temWaiters = this.list[index]
      deleteWaiters(temWaiters.id).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['username', 'limits', 'name', 'management', 'phone', 'email', 'region', 'pipeline', 'site', 'time', 'remark']
        const filterVal = ['username', 'limits', 'name', 'management', 'phone', 'email', 'region', 'pipeline', 'site', 'time', 'remark']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'time') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },

    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },

    getAllOptions() {
      fetchOptions().then(response => {
        this.regionOptions = response.data.regionOptions
        this.siteOptions = response.data.siteOptions
        this.pipelineOptions = response.data.pipelineOptions
        this.managementOptions = response.data.managementOptions
        this.limitsOptions = response.data.limitsOptions
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    }

  }
}
</script>

<style scoped>
.waitersBox {
  display: flex;
  flex-direction: column;
}
.waitersHeader{
  padding: 10px;
  display: flex;
  justify-content: center;
}
.administrationBody {
}
.administrationBodyTable {
  padding: 10px;
}
</style>
